package roborl;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Vector;

public class DiscreteValueApr extends ValueApproximate {

	HashMap<SP, Double> discreteFunction;

	// public DiscreteValueApr(){
	// super(null);
	// }
	public DiscreteValueApr(Vector<Action> as) {
		super(as);
		discreteFunction = new HashMap<SP, Double>();
	}

	static class SP implements Serializable {
		RobotState state;
		Action a;

		public SP(RobotState state, Action a) {
			this.a = a;
			this.state = state;
		}

		public boolean equals(Object o) {
			SP sp = (SP) o;
			boolean b = true;
			if (!a.toString().equals(sp.a.toString()))
				return false;

			Vector<String> ks = sp.state.getStateMeta();
			for (String k : ks) {
				if (Math.abs(sp.state.getState(k) - state.getState(k)) > 1e-3)
					b = false;
			}
			// for (int i = 0; i < s1.size(); i++) {
			// if (Math.abs(s1.get(i) - s2.get(i)) > 1e-3)
			// b = false;
			// }
			return b;
			// return sp.state.getStates().equals(state.getStates())
			// && a.equals(sp.a);
		}

		public String toString() {
			return a + "<->" + state.getStates();
		}

		public int hashCode() {
			return a.toString().hashCode();
		}
	}

	@Override
	public double getValue(RobotState robotState, Action action) {
		// TODO Auto-generated method stub
		Double d = discreteFunction.get(new SP(robotState, action));
		if (d == null)
			return 0;
		return d;
	}

	@Override
	public void updateValue(RobotState robotState, Action action,
			double newValue) {
		// TODO Auto-generated method stub
		// if (newValue >= 20)
		// System.currentTimeMillis();
		SP sp = new SP(robotState, action);
		discreteFunction.remove(sp);
		discreteFunction.put(sp, newValue);

		if (discreteFunction.size() > 10000) {
			throw new RuntimeException("States too large");
		}
	}

}
